package com.ruolin.micro.gateway.server.metadata;

import cn.hutool.core.map.MapUtil;
import com.ruolin.micro.gateway.server.constant.DubboMetadataConstant;
import org.apache.dubbo.registry.client.ServiceInstance;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class ServiceRouteMapping {
    private volatile Map<String, String> routeMapping = new ConcurrentHashMap<>();
    private volatile Set<String> routes = new HashSet<>();

    public void buildRouteMapping(ServiceInstance serviceInstance) {
        String methods = serviceInstance.getMetadata(DubboMetadataConstant.METHODS);
        if (methods.contains(",")) {
            String[] methodArray = methods.split(",");
            for (String method : methodArray) {
                routeMapping.put(method, serviceInstance.getServiceName());
            }
            return;
        }

        routeMapping.put(methods, serviceInstance.getServiceName());
    }

    public Map<String, String> getRouteMapping() {
        return routeMapping;
    }

    public Set<String> getRoutes() {
        return routes;
    }

    public List<String> getRoute(String serviceName) {
        if (MapUtil.isEmpty(routeMapping)) {

            return Collections.emptyList();
        }

        return routeMapping.entrySet()
                .stream()
                .filter(m -> m.getValue().equals(serviceName))
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

    }
}
